// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import Router from 'vue-router'

// 引入ElementUI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import { postRequest, putRequest, getRequest, deleteRequest } from './utils/api'
import './font-awesome/css/font-awesome.css'
import { initMenu } from './utils/menus'
// 插件
Vue.prototype.postRequest = postRequest
Vue.prototype.putRequest = putRequest
Vue.prototype.getRequest = getRequest
Vue.prototype.deleteRequest = deleteRequest

// 安装ElementUI
Vue.use(ElementUI, { size: 'small' })
Vue.use(Router)
Vue.config.productionTip = false

router.beforeEach((to, form, next) => {
  if (window.sessionStorage.getItem('tokenStr')) {
    initMenu(router, store)
    // 判断用户信息是否存在
    if (!window.sessionStorage.getItem('user')) {
      return getRequest('/admin/info').then(resp => {
        if (resp) {
          // 存入用户信息
          const userinfo = resp
          window.sessionStorage.setItem('user', JSON.stringify(userinfo))
          store.commit('INIT_ADMIN', resp)
          next()
        }
      })
    }
    next()
  } else {
    if (to.path === '/') {
      next()
    } else {
      next('/?redirect=' + to.path)
    }
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
